﻿
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MS.Core.Extensions;
using MS.Core.Helper;
using MS.Core.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.HPSF;
using ReportDesignerServer.DataModel;
using ReportDesignerServer.Services;
using ReportDesignerServer.Vo;
using System.IdentityModel.Tokens.Jwt;
using System.Text.Json.Nodes;

namespace ReportDesignerServer.Controllers
{
    /// <summary>
    /// 使用Hiprint提供数据源
    /// </summary>
    [Route("api/HiPrint")]
    [ApiController]
    public class HiPrintController : ControllerBase
    {
        HiPrintService hiPrintService;

        /// <summary>
        /// 报告模版路径
        /// </summary>
        private readonly string ReportPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Reports");
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="service"></param>
        public HiPrintController(HiPrintService service)
        {
            this.hiPrintService = service;
            if (!System.IO.Directory.Exists(ReportPath))
            {
                System.IO.Directory.CreateDirectory(ReportPath);
            }
        }

        /// <summary>
        /// 获取模版
        /// </summary>
        /// <param name="TemplateName"></param>
        /// <returns></returns>
        [HttpGet("GetReportTemplateByName")]
        public Rt GetTemplate(string? TemplateName = "TestReport")
        {
            SysHiprint sysHiprint = hiPrintService.GetSysHiprintByName(TemplateName);
            if (sysHiprint == null)
                return Rt.Fail("无法查询到模版");
            string jsonString = sysHiprint.templateText ?? "";
            dynamic jsonObject = JObject.Parse(jsonString);
            sysHiprint.templateObject = jsonObject;
            return Rt.SuccessObj(sysHiprint);
        }


        /// <summary>
        /// 获取模版
        /// </summary>
        /// <param name="TemplateName"></param>
        /// <returns></returns>
        [HttpGet("GetTempProviderByName")]
        public Rt GetTempProviderByName(string? TemplateName = "TestReport")
        {
            var printDataList = hiPrintService.GetPrintDataListByName(TemplateName);
            var jsonObject = printDataList.Select(c => new { Group = c.dataSourceKey, Colums = c.props.IsNullOrEmpty() ? null : JArray.Parse(c.props) }).ToList();
            return Rt.SuccessObj(jsonObject);
        }

        /// <summary>
        /// 保存模版
        /// </summary>
        /// <param name="sysHiprint"></param>
        /// <returns></returns>
        [HttpPost("SaveReportTemplateByName")]
        public Rt SaveTemplate([FromBody] SysHiprint sysHiprint)
        {
            //保存文件
            try
            {
                string path = Path.Combine(ReportPath, sysHiprint.templateCode + ".json");
                System.IO.File.WriteAllText(path, sysHiprint.templateText);
            }
            catch (Exception ex)
            {
                //文件操作失败
                NLogHelper.GetLog().Error(ex.ToString());
            }

            //保存到数据库
            if (hiPrintService.SaveSysHiprintByName(sysHiprint))
                return Rt.Success();
            else
                return Rt.Fail();
        }

        /// <summary>
        /// 获取模版的所有数据源列表
        /// </summary>
        /// <param name="TemplateName"></param>
        /// <returns></returns>
        [HttpGet("GetPrintDataListByName")]
        public Rt GetPrintDataListByName(string? TemplateName = "TestReport")
        {
            var printDataList = hiPrintService.GetPrintDataListByName(TemplateName);
            return Rt.SuccessObj(printDataList);
        }

        /// <summary>
        /// 获取数据源，取得数据源数据,，并返回
        /// </summary>
        /// <returns></returns>
        [HttpPost("LoadPrintData")]
        public Rt LoadPrintData(PrintDataParm printDataParm)
        {
            printDataParm = new PrintDataParm() { PrintTempName = "TestReport", Args = new List<string>() };
            JObject jobj = hiPrintService.GetPrintData(printDataParm.PrintTempName, printDataParm.Args.ToArray());
            return Rt.SuccessObj(jobj);
        }

        /// <summary>
        /// 获取数据源，取得数据源数据,，并返回
        /// </summary>
        /// <returns></returns>
        [HttpPost("SavePrintDataSource")]
        public Rt SavePrintDataSource(SysPrintData datasource)
        {
            if (hiPrintService.SavePrintDataSource(datasource))
                return Rt.Success();
            else
                return Rt.Fail();
        }

        /// <summary>
        /// 获取打印模版树
        /// </summary>
        /// <returns></returns>
        /// 

        [HttpGet("GetPrintTempTree")]
        public Rt GetPrintTempTree()
        {
            var sysHiprints = hiPrintService.GetAllPrintList();
            List<SysHiprint> prints = new List<SysHiprint>() { new SysHiprint() { id = 0, templateCode = "000", templateName = "打印模版", children = sysHiprints } };
            return Rt.SuccessObj(prints);
        }

    }
}
